/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName AuthSettingsHandler.as
 * @creationDate Aug 16, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.model.initialsetup.unversionedxmlhandlers.handlers
{
	import com.gesturesoft.imultimax.model.DataBaseManager;
	import com.gesturesoft.imultimax.model.error.DataBaseError;
	import com.gesturesoft.imultimax.model.interfaces.IDatabaseManager;
	import com.gesturesoft.imultimax.model.loader.events.LoadResultEvent;
	import com.gesturesoft.imultimax.model.utility.XMLUtilityParser;
	import com.gesturesoft.imultimax.model.vo.SettingsVO;
	
	import mx.collections.ArrayCollection;

	public class AuthSettingsHandler
	{
		public function AuthSettingsHandler()
		{
		}
		
		/**
		 * This is the function for inserting authentication settings to database
		 * 
		 * @functionName insertAuthSettings
		 * @creationDate Aug 16, 2012
		 * @author micmac
		 * @params arg:String
		 */
		public function insertAuthSettings(event:LoadResultEvent):void
		{
			
			var xmlParser:XMLUtilityParser = new XMLUtilityParser();
			var settings:ArrayCollection = xmlParser.parseAuthSettings(event.data);
			
			//START:Insert Authentication settings to database
			var dbManager:IDatabaseManager = new DataBaseManager();
			dbManager.setTransactionStartPoint();
			for each(var setting:SettingsVO in settings)
			{
				
				var query:String = "INSERT INTO IM_AUTH_SETTINGS(au_property, au_primary, au_secondary) VALUES('"+setting.property+"','"+setting.primary+"','"+setting.secondary+"' )";
				try
				{
					
					dbManager.execute(query);
					
				} 
				catch(error:DataBaseError) 
				{
					
					dbManager.rollBackTransactions();
					throw error;
					
					return;
					
				}
				
			}
			//END:Insert Authentication settings to database
			
			var apiSettings:ArrayCollection = xmlParser.parseAPISetings(event.data);
			
			//START:Insert api settings to database
			for each(var api:Object in apiSettings)
			{
				
				var apiQuery:String = "INSERT INTO IM_API_SETTINGS(api_name, email_required, api_required) VALUES('"+ api.name +"','"+ api.email +"','"+ api.required +"' )";
				try
				{
					
					dbManager.execute(apiQuery);
					
				} 
				catch(error:DataBaseError) 
				{
					
					dbManager.rollBackTransactions();
					throw error;
					//setErrorDisplay("Authentication Settings insertion failed");
					return;
					
				}
				
			}
			dbManager.commitTransaction();
			//END:Insert api codes to database
			
		}
		
	}
	
}